import Vue from 'vue'
import axios from 'axios';
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import App from './App.vue'
import router from './router'
import store from './store'
import { appid } from './config'
console.log(appid);

Vue.use(MintUI)
Vue.config.productionTip = false

Vue.prototype.$axios = axios
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;

Vue.prototype.$scaleHeight = function (size) {
  var docEl = document.documentElement
  return Math.round((size / 667) * docEl.clientHeight) + "px";
}

Vue.prototype.$scaleWidth = function (size) {
  var docEl = document.documentElement
  return Math.round((size / 375) * docEl.clientWidth) + "px";
}

router.beforeEach((to, from, next) => {
  getCode(to, next);
  // next()
});


// 从url中获得code
function getUrlParam() {
  var url = location.search;
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  return theRequest;
}

function getOpenId(code, next, to) {
  fetch(
    // 公司线上
    // `${process.env.VUE_APP_BASE_API}/redirect/wxd74edb5408c7d423/greet?code=${code}`,

    // 本地测试
    // `${process.env.VUE_APP_BASE_API}/redirect/wx124f5a74d20daac0/greet?code=${code}`,

    `${process.env.VUE_APP_BASE_API}/redirect/${appid}/greet?code=${code}`,
    {
      method: "GET"
    }
  )
    .then(res => {
      return res.text();
    })
    .then(text => {
      // alert(`获得到openId为${text}并且path为${to.path}`);

      text = JSON.parse(text)
      if (text.code != 0) {
        return Vue.prototype.toast({
          message: text.msg,
          position: "middle",
          duration: 1500
        });
      }
      if (typeof text.data == "string") {
        localStorage.setItem("openId", text.data);
        if (to.path == '/home') {
          next()
        }
      } else if (typeof text.data == "object") {
        localStorage.setItem("openId", text.data.openId);
        if (text.data.auditStatus == 0) {
          // if (to.path == '/verifyprocess') {
          next({
            path: '/verifyprocess'
          })
          // }
          return;
        }
        if (text.data.auditStatus == 1) {
          // 直接跳转到二维码页面
          // if (to.path == '/qrcode') {
          // 注意: 这种next传参数方式 会进行二次触发beforeEach

          next({
            path: '/qrcode',
            query: {
              data: JSON.stringify(text.data)
            }
          })
          // }
          return
        }
      }

    })
    .catch(() => { });
}

function getCode(to, next) {
  // next();
  // alert(localStorage.getItem('openId'))
  console.log(`${to.path}---${to.meta.requireAuth}`);
  if (to.path != '/home' || to.meta.requireAuth) {
    next();
    return
  }

  if (localStorage.getItem('openId')) {
    function getUserInfo(to, next) {
      fetch(
        `${process.env.VUE_APP_BASE_API}/village/household/${localStorage.getItem("openId")}`,
        {
          method: "GET"
        }
      )
        .then(res => {
          return res.text();
        })
        .then(text => {
          // alert(`${text}路径为${to.path}`)
          text = JSON.parse(text)
          if (text.code != 0 && !text.data) {
            if (to.path == '/home' || to.path == '/') {
              next();
            }
            return
          }
          if (text.data.auditStatus == 0) {
            next({
              path: "/verifyprocess" // 注意: 这种next传参数方式 会进行二次触发beforeEach
            })
            return
          } else if (text.data.auditStatus == 1) {
            next(`/qrcode?data=${JSON.stringify(text.data)}`) // 注意: 这种next传参数方式 会进行二次触发beforeEach
            return
          }
        })
        .catch(err => {
          alert(err)
        })
    }
    getUserInfo(to, next)
  } else {
    const code = getUrlParam().code;
    if (!code) {
      // 公司线上
      // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd74edb5408c7d423&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;

      // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd74edb5408c7d423&redirect_uri=${encodeURIComponent('http://wx.bangning.vip/wx')}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
      // alert(window.location.href)
      // 本地测试 
      // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx124f5a74d20daac0&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;

      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;

      // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx124f5a74d20daac0&redirect_uri=${encodeURIComponent("http://xuxingfeng.yicp.vip/bangning-h5")}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;


    } else {
      // alert(`code为${code}判断为${localStorage.getItem("code") &&
      // localStorage.getItem("code") == code}`)
      if (
        localStorage.getItem("code") &&
        localStorage.getItem("code") == code
      ) {
        return;
      }
      // 防止code二次使用
      localStorage.setItem("code", code);
      getOpenId(code, next, to);
    }
  }

}


(function (doc, win) {
  var docEl = doc.documentElement,
    resizeEvt =
      "orientationchange" in window ? "orientationchange" : "resize",
    recalc = function () {
      var clientWidth = docEl.clientWidth;
      if (!clientWidth) return;
      // Iphone6 和 IphoneX宽度一样 rem与px的比例一样 导致 高度方向 无法缩放
      docEl.style.fontSize = 16 * (clientWidth / 375) + "px";

      // 所以使用高度进行计算比例
      // docEl.style.fontSize = 16 * (docEl.clientHeight / 667) + "px";
      console.log(docEl.style.fontSize);
      doc.body.style.width = docEl.clientWidth + "px";
      doc.body.style.height = docEl.clientHeight + "px";
    };
  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false); //addEventListener事件方法接受三个参数：第一个是事件名称比如点击事件onclick，第二个是要执行的函数，第三个是布尔值
  doc.addEventListener("DOMContentLoaded", recalc, false); // 绑定浏览器缩放与加载时间
  doc.body.style.width = docEl.clientWidth + "px";
  doc.body.style.height = docEl.clientHeight + "px";

})(document, window);


// axios.interceptors.request.use(config => {
//   // config.headers.Token = `8d5148031fe9f9a857fefc9c981c733b`
//   let token = store.state.token
//   token && (config.headers.Token = `${token}`);
//   config.headers['Accept-Language'] = localStorage.getItem('currentLang') || 'zh-CN'
//   return config;
// },
//   err => {
//     return Promise.reject(err);
//   })



new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
